<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        {{ $route.params.id ? $route.meta.title : '编辑通用时长卡' }}
      </div>
      <i-form
        ref="form"
        class="agent-timecard-add_form"
        :items="formItems"
        :model="form"
        :rules="rules"
        :label-width="140"
        size="small"
      >
        <template slot="remark">
          <el-form-item>
            <div style="color: #988ca4">
              (注：默认无限天，自定义需大于等于7天)
            </div>
          </el-form-item>
        </template>
        <template slot="warning">
          <el-form-item>
            <div style="color: #988ca4">
              提示：该时长卡适用于本商户账号创建的所有电站，不支持下级运营商账号创建的电站
            </div>
          </el-form-item>
        </template>
        <template slot="isFloor">
          <el-form-item :required="true" label="是否按阶梯收费">
            <el-col style="line-height: 32px" :span="13">
              <div class="agent-timecard-add_form_power">
                <el-radio-group v-model="form.powerCharging">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
                <img
                  class="agent-timecard-add_form_help"
                  @click="handleShowTips"
                  src="@/assets/images/helpIcon.png"
                />
              </div>
            </el-col>
          </el-form-item>
        </template>
        <template slot="stationScale">
          <el-form-item :required="true" label="电站范围">
            <el-col>
              <el-radio-group
                v-model="form.stationScale"
                @change="changeStationScale"
              >
                <el-radio label="all">全部电站</el-radio>
                <el-radio label="apart">指定电站</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
        </template>
        <template slot="selectStation" v-if="form.stationScale === 'apart'">
          <el-form-item prop="station" class="is-required">
            <el-col :span="24">
              <TreeTransfer
                ref="treeTransfer"
                :title-left="'可选择电站'"
                :title-right="'已选择电站'"
                :data_left="dataLeft"
                :data_right="dataRight"
                :lazy="false"
                :showFilter="showFilter"
                @listenLeftTreeInfoEvent="bindLeftTreeInfoEvent"
                @listenRightTreeInfoEvent="bindRightTreeInfoEvent"
                :type="'common'"
              >
              </TreeTransfer>
            </el-col>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" v-loading="loading" @click="handleSubmit"
        >确认</el-button
      >
      <el-button type="warning" @click="handleCancel">取消</el-button>
    </div>
    <PowerChargingTip :visible.sync="tipsVisible" />
    <PackageDelWarnDlg
      v-if="warnDlgVisible"
      :visible.sync="warnDlgVisible"
      type="timeCard"
      operation="edit"
      :station-names="stationNames"
    >
    </PackageDelWarnDlg>
  </div>
</template>
<script>
import Big from 'big.js'
import TreeTransfer from '@/components/TreeTransfer'
import PowerChargingTip from '@/components/PowerChargingTip'
import PackageDelWarnDlg from './components/PackageDelWarnDlg'
import formValidate from '@/utils/validate'
import {
  insertMerchantTimecard,
  findMerchantStations,
  selectMerchantTimeCardDetail,
  updateMerchantTimeCard,
} from '@/api/mySelf'

export default {
  name: 'agentTimecardAdd',
  components: { TreeTransfer, PowerChargingTip, PackageDelWarnDlg },
  changeFormItemStatus(label, hidden) {
    const item = this.formItems.find((item) => {
      return item.label === label
    })

    if (item) {
      item.hidden = hidden
    }
  },
  methods: {
    bindRightTreeInfoEvent(data) {
      this.dataRight = data
      this.$refs.form.validateField('station')
    },
    bindLeftTreeInfoEvent(data) {
      this.dataLeft = data
    },
    handleCancel() {
      this.$router.push('/myself/agent-timecard-management')
    },
    handleShowTips() {
      this.tipsVisible = true
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        let params = {}
        if (!this.form.periodOfValidity || this.form.periodOfValidity == '') {
          params.periodOfValidity = 0
        } else {
          params.periodOfValidity = this.form.periodOfValidity
        }
        let strStationIds = ''
        if (this.form.stationScale !== 'all') {
          this.dataRight.forEach((item) => {
            strStationIds += `${item.id},`
          })
          strStationIds = strStationIds.substring(
            0,
            strStationIds.lastIndexOf(',')
          )
          params.stationIds = strStationIds
        }
        params = {
          ...params,
          price: this.form.price * 100,
          initialTime: this.form.initialTime,
          powerCharging: this.form.powerCharging,
        }

        this.loading = true
        if (this.$route.params.id) {
          updateMerchantTimeCard({
            id: this.$route.params.id,
            ...params,
          })
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '操作成功',
              })

              this.$router.push('/myself/agent-timecard-management')
            })
            .catch((err) => {
              if (err.code === 40030) {
                this.warnDlgVisible = true
                this.stationNames = err.data.join(',')
              }
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          insertMerchantTimecard(params)
            .then(() => {
              this.$message({
                type: 'success',
                showClose: true,
                message: '操作成功',
              })

              this.$router.push('/myself/agent-timecard-management')
            })
            .catch((err) => {
              console.log(err)
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    async changeStationScale(val) {
      if (val === 'apart') {
        this.dataRight = []
        let stations,
          tempArr = []
        stations = await findMerchantStations({
          currentPage: 1,
          pageSize: 10000,
        })
        if (Array.isArray(stations)) {
          stations.forEach((item) => {
            tempArr.push({
              name: item.stationName,
              id: item.id,
              leaf: true,
              visible: true,
            })
          })
        }
        this.dataLeft = tempArr || []
      }
    },
  },
  async created() {
    let stations,
      merchantTimeCardDetail,
      tempArr = []
    stations = await findMerchantStations({
      currentPage: 1,
      pageSize: 10000,
    })
    merchantTimeCardDetail =
      this.$route.params.id &&
      (await selectMerchantTimeCardDetail({
        id: parseInt(this.$route.params.id),
      }))
    if (Array.isArray(stations)) {
      stations.forEach((item) => {
        tempArr.push({
          name: item.stationName,
          id: item.id,
          leaf: true,
          visible: true,
        })
      })
    }
    if (merchantTimeCardDetail) {
      merchantTimeCardDetail.periodOfValidity === 0 &&
        delete merchantTimeCardDetail.periodOfValidity
      this.form = {
        ...this.form,
        initialTime: merchantTimeCardDetail.initialTime,
        periodOfValidity: merchantTimeCardDetail.periodOfValidity,
        powerCharging: merchantTimeCardDetail.powerCharging,
        price: merchantTimeCardDetail.price,
        stationIds: merchantTimeCardDetail.stationIds,
      }
      this.form.price = new Big(this.form.price / 100).toFixed(2)
      if (merchantTimeCardDetail.stationIds) {
        this.form.stationScale = 'apart'
        merchantTimeCardDetail.stations.forEach((item) =>
          this.dataRight.push({
            name: item.stationName,
            id: item.id,
            leaf: true,
            visible: true,
          })
        )
        for (let node of merchantTimeCardDetail.stations) {
          tempArr.forEach(
            (item) => (item.visible = item.visible && item.id !== node.id)
          )
        }
      }
    }
    this.dataLeft = tempArr || []
    if (this.dataRight.length) {
      this.$nextTick(() => {
        this.$refs.treeTransfer.filterNode('from')
      })
    }
  },
  data() {
    return {
      dataLeft: [],
      dataRight: [],
      tipsVisible: false,
      warnDlgVisible: false,
      showFilter: true,
      loading: false,
      type: 'add',
      formItems: [
        {
          label: '期限（天）',
          placeholder: '无限',
          type: 'inputNumber',
          value: 'periodOfValidity',
          class: 'agentTimecard-el-input',
          span: 14,
          min: 7,
          max: 999,
        },
        {
          slot: 'remark',
        },
        {
          label: '价格（元）',
          type: 'inputNumber',
          value: 'price',
          class: 'agentTimecard-el-input',
          span: 14,
          min: 0,
          max: 9999,
        },
        {
          label: '时长（小时）',
          type: 'inputNumber',
          class: 'agentTimecard-el-input',
          value: 'initialTime',
          span: 14,
          min: 1,
          max: 8640,
        },
        {
          slot: 'isFloor',
          required: true,
          span: 14,
        },
        {
          slot: 'stationScale',
        },
        {
          slot: 'selectStation',
          required: true,
        },
        {
          slot: 'warning',
        },
      ],
      form: {
        stationScale: 'all',
        powerCharging: false,
      },
      rules: {
        initialTime: [
          {
            emptymsg: '请输入时长',
            required: true,
            type: 'number',
            trigger: 'blur',
            message: '请输入时长',
          },
        ],
        price: [
          {
            emptymsg: '请输入价格',
            required: true,
            type: 'number',
            trigger: 'blur',
            message: '请输入价格',
          },
          {
            validator: formValidate('validatePrecisionTwo'),
            trigger: 'blur',
          },
        ],
        periodOfValidity: [
          {
            message: '需要大于等于7天',
            trigger: ['change', 'blur'],
            validator: (rule, value, callback) => {
              if (value && value < 7) {
                callback(new Error('需要大于等于7天'))
              } else {
                return callback()
              }
            },
          },
        ],
        powerCharging: [
          {
            message: '必选一项',
            required: true,
          },
        ],
        station: [
          {
            validator: (rule, value, callback) => {
              if (this.dataRight.length === 0) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
      },
    }
  },
}
</script>
<style lang="scss" scoped>
.agent-timecard-add_form {
  width: 820px;

  .agent-timecard-add_form_help {
    width: 20px;
    margin-left: 10px;
    cursor: pointer;
  }

  .agent-timecard-add_form_power {
    margin-top: 8px;
    display: flex;
    align-items: center;
    height: 100%;
  }
}
.i-form {
  &::v-deep .el-form-item.is-error .el-transfer-panel__body .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #d9d9d9;
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel {
    border-color: #ff4d4f;
  }
}
</style>
<style lang="scss">
.agentTimecard-el-input {
  .el-input-number {
    width: 320px;
  }
}
</style>
